package cn.com.pc.penguin.controllers;


import cn.com.pc.penguin.builder.keyword.KeywordSearchArgs;
import cn.com.pc.penguin.service.PenguinSearchResults;
import cn.com.pc.penguin.service.PenguinService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLDecoder;
import java.util.List;

@Controller
public class AutoCompleteController {
    @Autowired
    private PenguinService penguinService;

    @RequestMapping("/autoComplete")
    @ResponseBody
    public String autoComplete(@RequestParam String q) {
        long a = System.currentTimeMillis();
        JSONArray jsonArray = new JSONArray();
        try {
            String keyword = URLDecoder.decode(q, "utf-8").toLowerCase();
            KeywordSearchArgs args = new KeywordSearchArgs();
            args.setSuggestion(keyword);
            args.setOffset(0);
            args.setLimit(10);
            PenguinSearchResults result = penguinService.search(args);
            List<String> results = result.getLists();
            for (String res : results) {
                JSONObject jb = new JSONObject();
                jb.put("name", res);
                jsonArray.put(jb);
            }
            long b = System.currentTimeMillis();
           // System.out.println("autoComplete spent:" + (b - a) + "(ms)");
            return "parseSearchTips(" + jsonArray.toString() + ")";
        } catch (Exception e) {
            e.printStackTrace();  
        }
        return "";
    }

}
